package com.mzkj.wanjulaile.mobile.api.modules.appointment.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mzkj.common.data.StatusCode;
import com.mzkj.common.utils.StringUtils;
import com.mzkj.wanjulaile.mobile.api.common.controller.BaseController;
import com.mzkj.wanjulaile.mobile.api.common.entity.ResultEntity;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.Account;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.AccountService;
import com.mzkj.wanjulaile.mobile.api.modules.appointment.entity.AppointmentCollection;
import com.mzkj.wanjulaile.mobile.api.modules.appointment.service.AppointmentCollectionService;
import com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.service.ShoppingCartService;
import com.mzkj.wanjulaile.mobile.api.modules.toy.entity.Toy;
import com.mzkj.wanjulaile.mobile.api.modules.toy.service.ToyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "auth/appointmentCollection")
public class AppointmentCollectionAuthController extends BaseController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private AppointmentCollectionService appointmentCollectionService;
    @Autowired
    private ToyService toyService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Value("${pageSize}")
    private Integer pageSize;

    @Value("${maxPageSize}")
    private Integer maxPageSize;
    /**
     * 添加预约收藏
     * @param id   玩具id
     * @param type 分类  0：收藏  1:预约
     * @param  request  accessToken
     * @return
     */
    @RequestMapping(value = "addAppointmentCollection")
    @ResponseBody
    public ResultEntity<String> appointmentCollection(String id, String type, HttpServletRequest request) {
        ResultEntity<String> result = new ResultEntity<>();
        List<AppointmentCollection> appList ;
        List<AppointmentCollection> collectList ;
        String accountId=(String)request.getAttribute("accountId");
        try {
            AppointmentCollection appointmentCollection = new AppointmentCollection();
            Account account = accountService.get2(accountId);
            Toy toy = toyService.get(id);
            appointmentCollection.setType(type);
            appointmentCollection.setToy(toy);
            appointmentCollection.setAccount(account);
            if (AppointmentCollection.TYPE_COLLECTION.equals(type)) {
                collectList=appointmentCollectionService.getExists(appointmentCollection);
                //取消收藏
                if (collectList.size() > 0) {
                    appointmentCollectionService.cancelCollect(appointmentCollection);
                } else {
                    appointmentCollection.setIsNewRecord(true);
                    appointmentCollectionService.save(appointmentCollection);
                }
                result.setStatusCode(StatusCode.SC0.getValue());
                result.setMsg(StatusCode.SC0.getDesc());
            }
            if (AppointmentCollection.TYPE_APPOINTMENT.equals(type)) {
                appList = appointmentCollectionService.getExists(appointmentCollection);
                //是否重复预约
                if (appList.size() == 0) {
                    appointmentCollection.setToy(toy);
                    appointmentCollection.setAccount(account);
                    appointmentCollection.setIsNewRecord(true);
                    appointmentCollectionService.addAppColl(appointmentCollection);
                    result.setStatusCode(StatusCode.SC0.getValue());
                    result.setMsg(StatusCode.SC0.getDesc());
                } else {
                    result.setStatusCode(StatusCode.SC4004.getValue());
                    result.setMsg("玩具已预约");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

    /**
     * 获取预约,收藏玩具列表
     *
     * @param pageNum     每页数据大小
     * @param type        分类  0：收藏  1:预约
     * @param currentPage  当前页数
     * @param request      accessToken
     * @return
     */
    @RequestMapping(value = "getAppColl")
    @ResponseBody
    public ResultEntity<List<Toy>> getList(HttpServletRequest request, String pageNum, String type, Integer currentPage) {
        if(currentPage == null){
            currentPage=1;
        }
        if (!StringUtils.isEmpty(pageNum)) {
            if (Integer.valueOf(pageNum) > maxPageSize) {
                pageSize = maxPageSize;
            } else {
                pageSize = Integer.valueOf(pageNum);
            }
        }
        Toy toy = new Toy();
        String accountId=(String)request.getAttribute("accountId");
        Map<String, String> pageMap = Maps.newHashMap();
        pageMap.put("limit", "limit " + (currentPage - 1) * pageSize + "," + pageSize);
        toy.setSqlMap(pageMap);
        ResultEntity<List<Toy>> result = new ResultEntity<>();
        List<Toy> toyList = Lists.newArrayList();
//        if ("0".equals(type)) {
//            toy.setOnShelf("1");
//        }
        try {
            if (!StringUtils.isEmpty(accountId)) {
                Account account = new Account(accountId);
                AppointmentCollection appointmentCollection = new AppointmentCollection();
                appointmentCollection.setAccount(account);
                appointmentCollection.setType(type);
                toy.setAppointmentCollection(appointmentCollection);
                toyList = toyService.getListByType(toy);
            }
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
            result.setData(toyList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg(StatusCode.SC4002.getDesc());
            result.setData(toyList);
        }
        return result;
    }

    /**
     * 取消收藏
     *
     * @param id     玩具ID
     * @param   request  accessToken
     * @return
     */
    @RequestMapping(value = "cancelCollect")
    @ResponseBody
    public ResultEntity<String> cancel(String id,HttpServletRequest request) {
        ResultEntity<String> result = new ResultEntity<>();
        String accountId=(String)request.getAttribute("accountId");
        Account account =accountService.get2(accountId);
//        Account account = accountService.findAccountByOpenid(openID);
        AppointmentCollection appointmentCollection = new AppointmentCollection();
        if(StringUtils.isEmpty(id)){
            return new ResultEntity<>(StatusCode.SC4001);
        }
        Toy toy = new Toy();
        toy.setId(id);
        appointmentCollection.setAccount(account);
        appointmentCollection.setToy(toy);
        try {
            appointmentCollectionService.cancelCollect(appointmentCollection);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

    /**
     * 批量删除预约收藏记录
     * @param ids  预约收藏的id数组
     * @param type 类型 0：收藏  1:预约
     * @return
     */
    @RequestMapping(value = "batchDel")
    @ResponseBody
    public ResultEntity<String> batchDel(String ids,String type,HttpServletRequest request) {
        ResultEntity<String> result = new ResultEntity<>();
        String accountId=(String)request.getAttribute("accountId");
        try {
            if (!StringUtils.isEmpty(ids)) {
                String[] idArr = ids.split(",");
                for (String id : idArr) {
                    AppointmentCollection appointmentCollection = new AppointmentCollection();
                    appointmentCollection.setId(id);
                    appointmentCollectionService.delete(appointmentCollection);
                }
                //删除预约时,删除购物车
                if(AppointmentCollection.TYPE_APPOINTMENT.equals(type)){
                    if(!StringUtils.isEmpty(ids)){
                        List<String> idList= Arrays.asList(ids.split(","));
                        List<String> toyIdList=new ArrayList<String>();
                        for(String id:idList){
                            AppointmentCollection appointmentCollection=appointmentCollectionService.get(id);
                            toyIdList.add(appointmentCollection.getToy().getId());
                        }
                        shoppingCartService.batchDelete(toyIdList,accountId);
                    }
                }
            }
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }
}